package com.young.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.young.common.execption.ServiceException;
import com.young.common.utils.MD5Utils;
import com.young.common.utils.ToolUtils;
import com.young.manager.mapper.SysRoleMapper;
import com.young.manager.mapper.SysUserMapper;
import com.young.manager.mapper.SysUserRoleMapper;
import com.young.manager.model.SysRole;
import com.young.manager.model.SysUser;
import com.young.manager.model.SysUserRole;
import com.young.manager.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserServiceImpl implements SysUserService {

    private final SysUserMapper sysUserMapper;
    private final SysRoleMapper sysRoleMapper;
    private final SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Page<SysUser> queryUserList(String account, String name, String phone, Integer status, Integer pageNum, Integer pageSize) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(account)) queryWrapper.like("account", account);
        if (StringUtils.hasLength(name)) queryWrapper.like("name", name);
        if (StringUtils.hasLength(phone)) queryWrapper.like("phone", phone);
        if (null != status) queryWrapper.eq("status", status);
        queryWrapper.orderByDesc("create_time");
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        return sysUserMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<?> queryUserRoleIds(Long userId, Boolean simple) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("role_id").eq("user_id", userId);
        List<Long> roleIds = sysUserRoleMapper.selectObjs(queryWrapper);
        if (roleIds.isEmpty()) return Collections.EMPTY_LIST;
        List<SysRole> roleList = sysRoleMapper.selectBatchIds(roleIds);
        return simple ? roleList.stream().map(SysRole::getId).collect(Collectors.toList()) : roleList;
    }

    @Override
    public void insertSysUser(SysUser user) {
        // 账号和手机号是唯一的
        String account = user.getAccount();
        String phone = user.getPhone();
        if (!StringUtils.hasLength(account) && !StringUtils.hasLength(phone)) {
            throw new ServiceException("参数缺失！");
        }
        // 手机号填充为账号
        if (!StringUtils.hasLength(account)) {
            user.setAccount(phone);
        }
        // 判断账号是否存在
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        if (sysUserMapper.exists(queryWrapper)) {
            throw new ServiceException("账号已存在！");
        }
        if (StringUtils.hasLength(phone)) {
            queryWrapper.clear();
            queryWrapper.eq("phone", phone);
            if (sysUserMapper.exists(queryWrapper)) {
                throw new ServiceException("手机号已注册！");
            }
        }
        String salt = ToolUtils.generateRandomString(4);
        user.setSalt(salt);
        String encPassword = null == user.getPassword() ? MD5Utils.encrypt("123456" + salt) : MD5Utils.encrypt(user.getPassword() + salt);
        user.setPassword(encPassword);
        user.setStatus(1);
        if (null == user.getSuperUser()) user.setSuperUser(0);
        user.setCreateTime(new Date());
        user.setModifyTime(user.getCreateTime());
        if (sysUserMapper.insert(user) > 0) {
            if (user.getSuperUser().equals(1)) {
                Long[] roleIds = user.getRoleIds();
                if (roleIds.length > 0) {
                    List<SysUserRole> sysUserRoleList = new ArrayList<>();
                    for (Long roleId : roleIds) {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(user.getId());
                        sysUserRole.setRoleId(roleId);
                        sysUserRoleList.add(sysUserRole);
                    }
                    sysUserRoleMapper.insertBatchSomeColumn(sysUserRoleList);
                }
            }
        }
    }

    @Override
    public void updateSysUser(SysUser user) {
        if (null == user.getId()) {
            throw new ServiceException("参数缺失[id]！");
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount());
        SysUser existUser = sysUserMapper.selectOne(queryWrapper);
        if (null != existUser && !existUser.getId().equals(user.getId())) {
            throw new ServiceException("账号已存在！");
        }
        queryWrapper.clear();
        queryWrapper.eq("phone", user.getPhone());
        existUser = sysUserMapper.selectOne(queryWrapper);
        if (null != existUser && !existUser.getId().equals(user.getId())) {
            throw new ServiceException("手机号已被使用！");
        }
        if (sysUserMapper.updateById(user) > 0) {
            if (null != user.getSuperUser() && user.getSuperUser().equals(1)) {
                QueryWrapper<SysUserRole> deleteWrapper = new QueryWrapper<>();
                deleteWrapper.eq("user_id", user.getId());
                sysUserRoleMapper.delete(deleteWrapper);
            } else {
                Long[] roleIds = user.getRoleIds();
                if (roleIds.length > 0) {
                    QueryWrapper<SysUserRole> deleteWrapper = new QueryWrapper<>();
                    deleteWrapper.eq("user_id", user.getId());
                    sysUserRoleMapper.delete(deleteWrapper);
                    List<SysUserRole> sysUserRoleList = new ArrayList<>();
                    for (Long roleId : roleIds) {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setRoleId(roleId);
                        sysUserRole.setUserId(user.getId());
                        sysUserRoleList.add(sysUserRole);
                    }
                    sysUserRoleMapper.insertBatchSomeColumn(sysUserRoleList);
                }
            }
        }
    }

    @Override
    public void resetPassword(Long id, String newPassword) {
        newPassword = null == newPassword ? "123456" : newPassword;
        SysUser sysUser = sysUserMapper.selectById(id);
        if (null != sysUser) {
            String salt = ToolUtils.generateRandomString(4);
            sysUser.setSalt(salt);
            sysUser.setPassword(MD5Utils.encrypt(newPassword));
            sysUserMapper.updateById(sysUser);
        }
    }

    @Override
    public void deleteSysUser(Long userId) {
        sysUserMapper.deleteById(userId);
    }
}
